﻿using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Drawing;
using UsedBookTradeSystem.DBContext;
using UsedBookTradeSystem.Models.Dtos.InputDtos;
using UsedBookTradeSystem.Models.Entity;
using UsedBookTradeSystem.Models.Enum;

namespace UsedBookTradeSystem.Controllers.BackendControllers
{
    public class BookInfoController : Controller
    {
        private readonly SystemDbContext _ctx;

        public BookInfoController(SystemDbContext ctx)
        {
            _ctx = ctx;
        }
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> Index()
        {
            var bookList = await _ctx.BooksInfo.Include(x => x.Category).ToListAsync();
            ViewBag.BookList = bookList;
            return View();
        }
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> Add()
        {
            var categoryList = await _ctx.BookCategories.ToListAsync();
            ViewBag.CategoryList = categoryList;
            return View();
        }
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> Edit(int Id)
        {
            var BookInfo = await _ctx.BooksInfo.Include(x => x.Category).FirstAsync(x => x.Id == Id);
            var categoryList = await _ctx.BookCategories.ToListAsync();
            ViewBag.CategoryList = categoryList;
            ViewBag.BookInfo = BookInfo;
            return View();
        }
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> AddBookInfo(BookInfoInput bookInfoInput, IFormFile Picture)
        {
            if (string.IsNullOrWhiteSpace(bookInfoInput.BookName) ||
                string.IsNullOrWhiteSpace(bookInfoInput.Author) ||
                string.IsNullOrWhiteSpace(bookInfoInput.BookDetail) ||
                string.IsNullOrWhiteSpace(bookInfoInput.Bookspecs) ||
                string.IsNullOrWhiteSpace(bookInfoInput.Press))
            {
                TempData["OperateResult"] = "输入不合法";
                return RedirectToAction(nameof(Add));
            }
            if (Picture == null || Picture.Length == 0)
            {
                TempData["OperateResult"] = "请上传图片";
                return RedirectToAction(nameof(Add));
            }
            try
            {
                //保存图片
                using var image = Image.FromStream(Picture.OpenReadStream());
                var fileName = Guid.NewGuid().ToString().Replace("-", "") + ".";
                var savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", fileName + Picture.FileName.Split(".")[1]);
                using var stream = System.IO.File.Create(savePath);
                Picture.CopyTo(stream);
                BookInfo bookInfo = new()
                {
                    BookName = bookInfoInput.BookName,
                    Author = bookInfoInput.Author,
                    BookDetail = bookInfoInput.BookDetail,
                    Bookspecs = bookInfoInput.Bookspecs,
                    Press = bookInfoInput.Press,
                    Picture = "/uploads/" + fileName + Picture.FileName.Split(".")[1],
                    Price = bookInfoInput.Price,
                    Inventory = bookInfoInput.Inventory,
                    Category = _ctx.BookCategories.First(x => x.Id == bookInfoInput.Category)
                };
                List<Book> bookList = new();
                for (int i = 0; i < bookInfo.Inventory; i++)
                {
                    bookList.Add(new Book { BookInfo = bookInfo, Price = bookInfo.Price });
                }
                await _ctx.BooksInfo.AddAsync(bookInfo);
                await _ctx.Books.AddRangeAsync(bookList);
                await _ctx.SaveChangesAsync();
            }
            catch (ArgumentException)
            {
                TempData["OperateResult"] = "请上传图片";
                return RedirectToAction(nameof(Add));
            }
            return RedirectToAction(nameof(Index));
        }
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> UpdateBookInfo(BookInfoInput bookInfoInput, IFormFile Picture)
        {
            if (string.IsNullOrWhiteSpace(bookInfoInput.BookName) ||
                string.IsNullOrWhiteSpace(bookInfoInput.Author) ||
                string.IsNullOrWhiteSpace(bookInfoInput.BookDetail) ||
                string.IsNullOrWhiteSpace(bookInfoInput.Bookspecs) ||
                string.IsNullOrWhiteSpace(bookInfoInput.Press))
            {
                TempData["OperateResult"] = "输入不合法";
                return RedirectToAction(nameof(Edit));
            }
            try
            {
                string? savePath = null;
                if (Picture != null && Picture.Length != 0)
                {
                    //保存图片
                    using var image = Image.FromStream(Picture.OpenReadStream());
                    var fileName = Guid.NewGuid().ToString().Replace("-", "") + ".";
                    savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", fileName + Picture.FileName.Split(".")[1]);
                    using var stream = System.IO.File.Create(savePath);
                    Picture.CopyTo(stream);
                    savePath = "/uploads/" + fileName + Picture.FileName.Split(".")[1];
                }
                //查询书籍信息
                BookInfo bookInfo = await _ctx.BooksInfo.Include(x => x.Category).FirstAsync(x => x.Id == bookInfoInput.Id);
                bookInfo.BookName = bookInfoInput.BookName;
                bookInfo.Press = bookInfoInput.Press;
                bookInfo.Author = bookInfoInput.Author;
                bookInfo.Picture = savePath ?? bookInfo.Picture;
                bookInfo.Bookspecs = bookInfoInput.Bookspecs;
                bookInfo.BookDetail = bookInfoInput.BookDetail;
                bookInfo.Price = bookInfoInput.Price;
                bookInfo.Inventory = bookInfoInput.Inventory;
                bookInfo.Category = await _ctx.BookCategories.FirstAsync(x => x.Id == bookInfoInput.Category);
                bookInfo.UpdatedTime = DateTime.Now;
                //查询该信息下所有未买的书籍
                List<Book> bookList = await _ctx.Books.Where(x => x.BookInfo == bookInfo && x.IsSell == false && x.Cart==null).ToListAsync();
                foreach (var book in bookList)
                {
                    book.Price = bookInfo.Price;
                    book.UpdatedTime = DateTime.Now;
                }
                var UpdateCount = bookInfo.Inventory - bookList.Count;
                if (UpdateCount < -bookList.Count)
                {
                    TempData["OperateResult"] = "库存不能为负";
                    return RedirectToAction(nameof(Edit));
                }
                if (UpdateCount >= 0)
                {
                    for (int i = 0; i < UpdateCount; i++)
                    {
                        bookList.Add(new Book { BookInfo = bookInfo, Price = bookInfo.Price });
                    }
                }
                else
                {
                    for (int i = 0; i < Math.Abs(UpdateCount); i++)
                    {
                        bookList[i].UpdatedTime = DateTime.Now;
                        bookList[i].IsDeleted = true;
                    }
                }
                _ctx.BooksInfo.Update(bookInfo);
                _ctx.Books.UpdateRange(bookList.Where(x => x.Id != 0).ToList());
                await _ctx.Books.AddRangeAsync(bookList.Where(x => x.Id == 0).ToList());
                await _ctx.SaveChangesAsync();
            }
            catch (ArgumentException)
            {
                TempData["OperateResult"] = "请上传图片";
                return RedirectToAction(nameof(Edit));
            }
            return RedirectToAction(nameof(Index));
        }
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> Delete(int Id)
        {
            var bookinfo = await _ctx.BooksInfo.Include(x => x.Books).FirstAsync(x => x.Id == Id);
            bookinfo.UpdatedTime = DateTime.Now;
            bookinfo.IsDeleted = true;
            bookinfo.Inventory = 0;
            if (bookinfo.Books != null)
            {
                foreach (var book in bookinfo.Books)
                {
                    book.UpdatedTime = DateTime.Now;
                    book.IsDeleted = true;
                }
            }
            _ctx.BooksInfo.Update(bookinfo);
            await _ctx.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }
}
